package IBBB.network.sendmessage;

import server.User;
import IBBB.model.UserMessage;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class send_login extends send_String {
    public UserMessage getUserMessage() {
        return userMessage;
    }

    private UserMessage userMessage;

    Map<String, String> map = new LinkedHashMap<>();
    {
        map.put("cet4", "四级真题词汇");
        map.put("cet6", "六级真题词汇");
        map.put("kaoyan", "考研英语基础");
        map.put("toefl", "托福词汇");
        map.put("ielts", "雅思词汇");
    }
    public send_login(String server, String username, String password) {
        super(server);
        target_message="UserLogin#"+username+"#"+password;
    }

    @Override
    public Void call() {
        User user;
        Socket client = new Socket();
        try {
            client.connect(message_socket, 3000);
        } catch (Exception e) {
            updateMessage("timeout");
            return null;
        }


        try (ObjectOutputStream write = new ObjectOutputStream(client.getOutputStream())) {
            try (ObjectInputStream reader = new ObjectInputStream(client.getInputStream())) {
                write.writeObject(target_message);
                Object o = reader.readObject();
                client.close();
                if (o == null) {
                    updateMessage("nameOrPasswordWrong");
                } else {
                    user = (User) o;
                    Map<String, List<Integer>> sche = user.getSchedules();
                    Map<String, List<Integer>> newSche = new HashMap<String, List<Integer>>();
                    for (Map.Entry<String, List<Integer>> item: sche.entrySet()){
                        System.out.println(item.getKey());//TODO
                        newSche.put(map.get(item.getKey()), item.getValue());
                    }

                    userMessage = new UserMessage(user.getName(), newSche);
                    updateMessage("success");
                }
            }
        } catch (Exception e) {
            updateMessage("wrong");
        }
        return null;
    }
}
